<template>
  <ContentContainer :loading="loading" :pagination="pagination" @run="run">
    <template #header>
      <a-button type="primary" @click="open">
        <i-icons-btn-add />
        添加节点
      </a-button>

      <CloudFilterBar
        v-model="queryParams"
        :run="run"
        :schemes="filterScheme"></CloudFilterBar>
    </template>
    <a-table
      ref="tableRef"
      v-model:selected-keys="selectedKeys"
      v-bind="commonTableProps"
      :columns="columns"
      :data="data"
      :row-selection="defaultRowSelection"
      @sorter-change="onSorterChange"
      @selection-change="onSelectChange">
      <template #name="{ record }">
        <!-- <span
          class="cursor-pointer"
          :class="{ 'text-primary': record.installed }"
          @click="toManagement(record)"
          >{{ record.name || '-' }}</span
        > -->
        <div>
          <TextEll v-if="!record.installed" class="text-[#ADAFB2]">{{
            record.name || '-'
          }}</TextEll>
          <TextEll
            v-else
            class="text-[#1D2129] cursor-pointer"
            @click="toManagement(record)">
            <div class="table-link-text">{{ record.name || '-' }}</div>
          </TextEll>
          <!-- <span v-if="!record.installed" class="text-[#ADAFB2]">{{
            record.name || '-'
          }}</span>
          <div
            v-else
            class="text-[#1D2129] cursor-pointer table-link-text"
            @click="toManagement(record)">
            {{ record.name || '-' }}
          </div> -->
        </div>
      </template>
      <template #ip="{ record }">
        <div v-if="record.ips.filter(Boolean).length > 0" class="common-box">
          <span>{{ record.ips[0] }}</span>
          <a-popover v-if="record.ips.length > 1">
            <i-icons-base-info class="table-icon" />
            <template #content>
              <div class="text-1 font-bold">IP</div>
              <template v-for="(ip, i) in record.ips" :key="ip">
                <div class="flex items-center gap-x-2">
                  <span>{{ ip }}<span v-if="i === 0">(主)</span> </span>
                  <i-icons-copy
                    class="text-7 hover:text-2 cursor-pointer"
                    @click="handleCopy(ip)" />
                </div>
              </template>
            </template>
          </a-popover>
        </div>
        <span v-else>-</span>
      </template>

      <template #status="{ record }">
        <div v-if="Number(record.status) > 0" class="common-box">
          <i-icons-node-normal v-if="record.status === 1" />
          <i-icons-warning v-if="record.status === 2" />
          <i-icons-node-stop v-if="record.status === 3" />
          <i-icons-failed v-if="record.status === 4" />
          <i-icons-node-init v-if="record.status === 5" />
          <span>{{ getOptionsLabel(nodeStatusOptions, record.status) }}</span>
          <a-dropdown
            v-if="record.status !== 5"
            content-class="table-dropdown"
            @select="(v) => handleCommand(v as string, [record.id],record)">
            <i-icons-more-action class="table-icon" />
            <template #content>
              <a-doption value="startOne" :disabled="record.status === 1">
                启用
              </a-doption>
              <a-doption value="stopOne" :disabled="record.status === 3">
                停用
              </a-doption>
              <a-doption value="reloadOne" :disabled="record.status === 3">
                重启
              </a-doption>
            </template>
          </a-dropdown>
        </div>
        <span v-else>-</span>
      </template>
      <template #resolve_status="{ record }">
        <div v-if="record.cascade_level === 1" class="common-box">
          <span
            :class="[
              'text-primary',
              { 'text-4!': record.resolve_status !== 1 }
            ]">
            {{ record.resolve_status === 1 ? '已解析' : '未解析' }}
          </span>
          <a-dropdown
            v-if="record.installed && record.status !== 5"
            content-class="table-dropdown"
            @select="(v) => handleCommand(v as string, [record.id],record)">
            <i-icons-more-action class="table-icon" />
            <template #content>
              <a-doption
                value="join"
                :disabled="Number(record.resolve_status) === 1">
                加入解析
              </a-doption>
              <a-doption
                value="remove"
                :disabled="Number(record.resolve_status) !== 1">
                移除解析
              </a-doption>
            </template>
          </a-dropdown>
        </div>
        <span v-else>-</span>
      </template>
      <template #version="{ record }">
        <div class="common-box gap-x-0!">
          <span>{{ record.version || '-' }}</span>
          <i-icons-upgrade
            v-if="!record.is_latest_version && record.version"
            class="cursor-pointer"
            @click="handleCommand('version', [record.id], record)" />
          <a-popover v-if="record.installed && record.is_requires_upgrade">
            <template #content>
              <div class="flex items-center gap-6px">
                <i-icons-triangle-red class="ml-[6px]" />
                <span class="text-[#393C40]">节点配置不兼容，请立即升级</span>
              </div>
            </template>
            <i-icons-triangle-red class="ml-[6px] cursor-pointer" />
          </a-popover>
          <!-- <i-icons-update v-if="!record.is_latest_version && record.version" />
          <i-icons-change
            v-if="record.version"
            class="table-icon ml-6px"
            @click="handleCommand('version', [record.id], record)" /> -->
        </div>
      </template>
      <template #os="{ record }">
        <a-tooltip v-if="record.platform">
          <i-icons-ubuntu
            v-if="isPlatform(record.platform, 'ubuntu')"
            size="6" />
          <i-icons-centos
            v-else-if="isPlatform(record.platform, 'centos')"
            size="6" />
          <i-icons-debian
            v-else-if="isPlatform(record.platform, 'debian')"
            size="6" />
          <i-icons-rocky-linux
            v-else-if="isPlatform(record.platform, 'rocky')"
            size="6" />
          <i-icons-unix v-else size="6" />
          <template #content
            >{{ record.platform }} {{ record.platform_version || '' }}</template
          >
        </a-tooltip>
        <span v-else>-</span>
      </template>
      <template #action="{ record }">
        <a-link
          v-if="record.installed"
          :hoverable="false"
          @click="toManagement(record)">
          管理
        </a-link>
        <a-link
          v-else
          :hoverable="false"
          @click="handleCommand('install_script', [record.id])">
          安装
        </a-link>
        <a-link
          :hoverable="false"
          status="danger"
          @click="handleCommand('delete', [record.id], record)">
          删除
        </a-link>
      </template>
    </a-table>
    <template #footer-prefix>
      <div class="common-box gap-x-4!">
        <a-button
          :disabled="selectedKeys.length < 1"
          @click="handleCommand('start', selectedKeys as string[] )">
          启用
        </a-button>
        <a-button
          :disabled="selectedKeys.length < 1"
          @click="handleCommand('reload', selectedKeys as string[] )">
          重启
        </a-button>
        <a-button
          :disabled="selectedKeys.length < 1"
          @click="handleCommand('stop', selectedKeys as string[] )">
          停用
        </a-button>
        <a-dropdown
          @select="(v) => handleCommand(v as string, selectedKeys as string[],selectionRows[0])">
          <a-button :disabled="selectedKeys.length < 1">
            更多
            <IconDown />
          </a-button>
          <template #content>
            <a-doption value="config">同步配置</a-doption>
            <a-doption value="cache">清理缓存</a-doption>
            <a-doption value="version">升级版本</a-doption>
          </template>
        </a-dropdown>
      </div>
    </template>
    <AddNode v-model="visible" @reload="run"></AddNode>
  </ContentContainer>
</template>
<script lang="tsx" setup>
import type { NodeListItem } from '@/apis/model/node'
import { getApiNodeQueryApi } from '@/apis/modules/node/node'
import { commonTableProps, defaultRowSelection } from '@/utils/table'
import { IconDown } from '@arco-design/web-vue/es/icon'
import { useClipboard } from '@vueuse/core'
import useCommand from './actions'
import useTableColumn from './columns'
import AddNode from './components/AddNode.vue'

const { columns, filterScheme } = useTableColumn()
const { visible, open } = usePopup()
const router = useRouter()
const { copy } = useClipboard({
  legacy: true
})
const queryParams = ref({
  limit: 20
})
const data = ref<NodeListItem[]>([])
const { loading, run, pagination } = useListRequest(getApiNodeQueryApi, {
  immediate: true,
  params: queryParams,
  afterFn(res) {
    //未安装节点添加disabled属性
    data.value =
      res?.list?.map((v: NodeListItem) => {
        if (v.installed) return v
        return Object.assign(v, { disabled: true })
      }) ?? []
  }
})
const { handleCommand } = useCommand(run)
const {
  selectedKeys,
  tableRef,
  selectionRows,
  onSelectChange,
  createSortChange
} = useTable(run, data)
const onSorterChange = createSortChange(queryParams)
const toManagement = (row: NodeListItem) => {
  if (row.installed) {
    router.push({ name: 'NodeManagement', params: { id: row.id } })
  }
}

const handleCopy = (content: string) => {
  copy(String(content)).then(() => {
    ToastUtils.success('复制成功')
  })
}

const isPlatform = (
  platform: string | undefined,
  targetPlatform: string
): boolean => {
  return platform?.toUpperCase() === targetPlatform.toUpperCase()
}
</script>
<style lang="less" scoped>
.arco-table-tr:hover .table-link-text {
  color: #165dff;
}

.common-box {
  @apply flex gap-x-6px items-center;
}
</style>
